package cn.cutie.clotconfig.client.config;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

/**
 * @Description: 配置文件处理器
 * PriorityOrdered 来确保让它第一个执行，等同于加@Order配置，但是不同加@Component，@Service之类的注解
 * @Author: Cutie
 * @CreateDate: 2024/5/10 20:22
 * @Version: 0.0.1
 */
@Data
public class PropertySourcesProcessor implements BeanFactoryPostProcessor, EnvironmentAware, PriorityOrdered, ApplicationContextAware {

    private final static String CLOT_PROPERTY_SOURCES = "ClotPropertySources";
    private final static String CLOT_PROPERTY_SOURCE = "ClotPropertySource";

    ApplicationContext applicationContext;

    Environment environment;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ConfigurableEnvironment ENV = (ConfigurableEnvironment) environment;
        if (ENV.getPropertySources().contains(CLOT_PROPERTY_SOURCES)){
            return;
        }
        // 通过http请求 clot-server 获取配置
//        Map<String, String> config = new HashMap<>();
//        config.put("clot.a", "dev-a-100");
//        config.put("clot.b", "dev-b-200");
//        config.put("clot.c", "dev-c-300");

        String app = ENV.getProperty("clotconfig.app", "app1");
        String env = ENV.getProperty("clotconfig.env", "dev");
        String ns = ENV.getProperty("clotconfig.ns", "public");
        String configServer = ENV.getProperty("clotconfig.configServer", "http://localhost:9129");
        ConfigMeta configMeta = new ConfigMeta(app, env, ns, configServer);

        ClotConfigService clotConfigService = ClotConfigService.getDefault(applicationContext, configMeta);
        ClotPropertySource clotPropertySource = new ClotPropertySource(CLOT_PROPERTY_SOURCE, clotConfigService);
        CompositePropertySource composite = new CompositePropertySource(CLOT_PROPERTY_SOURCES);
        composite.addPropertySource(clotPropertySource);
        ENV.getPropertySources().addFirst(composite);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
